﻿#include "mm_service.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QDateTime>
#include <QFile>
#include "RecorderService/recorder-app.h"

MMService::MMService(QObject *parent)
    : QObject(parent)
    , m_rtcClient(nullptr)
    , m_initialized(false)
    , m_recorderApp(nullptr)
    , m_rtcRecorder(nullptr)
{
}

MMService::~MMService()
{
    stop();
    
    if (m_rtcClient) {
        delete m_rtcClient;
        m_rtcClient = nullptr;
    }
    
    if (m_rtcRecorder) {
        delete m_rtcRecorder;
        m_rtcRecorder = nullptr;
    }
}

bool MMService::initialize(const QString &serviceType, const RecordingConfig &config)
{
    if (m_initialized) {
        qWarning() << "MMService already initialized";
        return true;
    }
    
    m_serviceType = serviceType;
    m_recordingConfig = config;
    
    qDebug() << "[MMSERVICE] Initializing MMService with type:" << serviceType;
    
    // 直接输出到stderr，绕过日志分类
    fprintf(stderr, "[MMSERVICE-DEBUG] Recording mode: '%s'\n", config.recordingMode.toUtf8().constData());
    fprintf(stderr, "[MMSERVICE-DEBUG] Service type: '%s'\n", serviceType.toUtf8().constData());
    fflush(stderr);
    
    qDebug() << "[MMSERVICE] MMService config - Log:" << config.logPath
             << "User:" << config.userName
             << "ID:" << config.userId
             << "Server:" << config.serverName
             << "Mode:" << config.recordingMode;
    
    // 创建 RTC 客户端，连接到 Teacher 端的 RTCService
    qDebug() << "[MMSERVICE] Creating RTC client...";
    m_rtcClient = new RTCClient(this);
    if (!m_rtcClient) {
        qDebug() << "[MMSERVICE] FAILED to create RTC client";
        emit error("Failed to create RTC client");
        return false;
    }
    qDebug() << "[MMSERVICE] RTC client created successfully";
    
    // 设置MMService指针到RTCClient，以便音频帧能够正确转发
    qDebug() << "[MMSERVICE] Setting MMService pointer to RTCClient...";
    m_rtcClient->setMMService(this);
    qDebug() << "[MMSERVICE] MMService pointer set to RTCClient";
    
    // 连接 RTC 客户端的退出信号
    qDebug() << "[MMSERVICE] Connecting RTCClient exit signal...";
    bool connected = connect(m_rtcClient, &RTCClient::exit, this, [this]() {
        qDebug() << "[MMSERVICE] RTC Client requested exit";
        emit serviceStopped();
    });
    
    if (!connected) {
        qDebug() << "[MMSERVICE] FAILED to connect RTCClient::exit signal!";
        emit error("Failed to connect RTCClient exit signal");
        return false;
    } else {
        qDebug() << "[MMSERVICE] Successfully connected RTCClient::exit signal";
    }
    
    // 连接到 Teacher 端的 RTCService
    qDebug() << "[MMSERVICE] Connecting to Teacher RTCService...";
    m_rtcClient->connectToTeacher();
    qDebug() << "[MMSERVICE] Connection request sent to Teacher RTCService";
    
    // 如果是RTC麦克风模式，准备音频帧观察者配置（但不立即注册）
    if (serviceType == "teacher" && config.recordingMode == "rtc-mic") {
        qDebug() << "[MMSERVICE] RTC microphone mode detected - preparing audio frame observer config";
        
        // 配置音频帧观察者参数
        RTC3::RtcEngineAudioFrameObserverConfig audioConfig;
        
        // 将采样率数值转换为枚举值
        switch (config.rtcAudioSampleRate) {
            case 8000:
                audioConfig.sampleRate = RTC3::RtcEngineAudioSampleRate_8000;
                break;
            case 16000:
                audioConfig.sampleRate = RTC3::RtcEngineAudioSampleRate_16000;
                break;
            case 32000:
                audioConfig.sampleRate = RTC3::RtcEngineAudioSampleRate_32000;
                break;
            case 44100:
                audioConfig.sampleRate = RTC3::RtcEngineAudioSampleRate_44100;
                break;
            case 48000:
            default:
                audioConfig.sampleRate = RTC3::RtcEngineAudioSampleRate_48000;
                break;
        }
        
        audioConfig.channels = config.rtcAudioChannels == 1 ? RTC3::RtcEngineMonoAudio : RTC3::RtcEngineStereoAudio;
        audioConfig.permission = RTC3::RtcEngineAudioFrameReadOnly;
        
        // 设置音频帧观察者配置
        qDebug() << "[MMSERVICE] Setting audio frame observer config...";
        m_rtcClient->setAudioFrameObserverConfig(audioConfig);
        qDebug() << "[MMSERVICE] Audio frame observer config set";
        
        qDebug() << "[MMSERVICE] Audio frame observer config prepared:"
                 << "sampleRate:" << config.rtcAudioSampleRate
                 << "channels:" << config.rtcAudioChannels
                 << "format:" << config.rtcAudioFormat << "bit";
        qDebug() << "[MMSERVICE] Note: Audio frame observer will be registered when RTC engine is created";
        qDebug() << "[MMSERVICE] Note: Audio frame observer will be enabled when recording starts";
    } else if (serviceType == "teacher" && config.recordingMode == "device") {
        qDebug() << "[MMSERVICE] Device recording mode detected - no audio frame observer needed";
        // 在设备模式下，不创建音频帧观察者以节省资源
    }
    
    // 只有教师端才创建录制应用
    if (serviceType == "teacher") {
        qDebug() << "[RECORDER] Creating recorder app for teacher mode";
        qDebug() << "[RECORDER] Recording mode is:" << config.recordingMode;
        
        // 根据录制模式创建相应的录制器
        if (config.recordingMode == "rtc-mic") {
            qDebug() << "[RECORDER] Entering RTC recording mode branch";
            
            // RTC模式：先创建RecorderClient（与设备模式完全一致）
            qDebug() << "[RECORDER] Creating RecorderClient for RTC mode (identical to device mode)...";
            m_recorderApp = new ZDTalkRecorder(this);
            if (!m_recorderApp) {
                qDebug() << "[RECORDER] FAILED to create recorder app for RTC mode";
                emit error("Failed to create recorder app for RTC mode");
                return false;
            }
            qDebug() << "[RECORDER] RecorderClient created for RTC mode";
            
            // 在初始化之前应用配置（与设备模式完全一致）
            qDebug() << "[RECORDER] Applying recording configuration for RTC mode...";
            applyRecordingConfig(config);
            qDebug() << "[RECORDER] Recording configuration applied for RTC mode";
            
            // 初始化录制应用，使用配置中的服务器名称（与设备模式完全一致）
            QString targetServerName = config.serverName.isEmpty() ? "ZDTalkRecorder" : config.serverName;
            qDebug() << "[RECORDER] Initializing RecorderClient for RTC mode with server name:" << targetServerName;
            
            qDebug() << "[RECORDER] About to call m_recorderApp->Init() for RTC mode...";
            if (m_recorderApp->Init(targetServerName, "") != 0) {
                qDebug() << "[RECORDER] FAILED to initialize recorder app for RTC mode";
                emit error("Failed to initialize recorder app for RTC mode");
                return false;
            }
            
            qDebug() << "[RECORDER] RecorderClient initialized successfully for RTC mode";
            
            // 现在创建RTCRecorder（在RecorderClient初始化完成后）
            qDebug() << "[RECORDER] Creating RTC recorder for audio processing...";
            try {
                m_rtcRecorder = new RTCRecorder(this);
                qDebug() << "[RECORDER] RTCRecorder constructor completed";
                
                if (!m_rtcRecorder) {
                    qDebug() << "[RECORDER] FAILED to create RTC recorder - pointer is null";
                    emit error("Failed to create RTC recorder");
                    return false;
                }
                qDebug() << "[RECORDER] RTC recorder created successfully";
                
            } catch (const std::exception& e) {
                qDebug() << "[RECORDER] EXCEPTION during RTCRecorder creation:" << e.what();
                emit error("Exception during RTC recorder creation");
                return false;
            } catch (...) {
                qDebug() << "[RECORDER] UNKNOWN EXCEPTION during RTCRecorder creation";
                emit error("Unknown exception during RTC recorder creation");
                return false;
            }
            
            // 配置RTC录制器
            qDebug() << "[RECORDER] Configuring RTC recorder...";
            RTCRecorderConfig rtcConfig;
            rtcConfig.logPath = config.logPath;
            rtcConfig.crashPath = config.crashPath;
            rtcConfig.userName = config.userName;
            rtcConfig.userId = config.userId;
            rtcConfig.sampleRate = config.rtcAudioSampleRate;
            rtcConfig.channels = config.rtcAudioChannels;
            rtcConfig.audioFormat = QString::number(config.rtcAudioFormat);
            qDebug() << "[RECORDER] RTC recorder config prepared";
            
            qDebug() << "[RECORDER] Initializing RTC recorder...";
            try {
                if (!m_rtcRecorder->initialize(rtcConfig)) {
                    qDebug() << "[RECORDER] FAILED to initialize RTC recorder";
                    emit error("Failed to initialize RTC recorder");
                    return false;
                }
                qDebug() << "[RECORDER] RTC recorder initialized successfully";
                
            } catch (const std::exception& e) {
                qDebug() << "[RECORDER] EXCEPTION during RTC recorder initialization:" << e.what();
                emit error("Exception during RTC recorder initialization");
                return false;
            } catch (...) {
                qDebug() << "[RECORDER] UNKNOWN EXCEPTION during RTC recorder initialization";
                emit error("Unknown exception during RTC recorder initialization");
                return false;
            }
            
            // 连接RecorderClient的信号到RTCRecorder
            RecorderClient *recorderClient = m_recorderApp->getRecorderClient();
            if (recorderClient) {
                qDebug() << "[RECORDER] Connecting RecorderClient signals to RTCRecorder...";
                
                // 连接OBS初始化完成信号，让RTCRecorder在OBS初始化后设置音频源
                connect(recorderClient, &RecorderClient::OnOBSInited, 
                        m_rtcRecorder, &RTCRecorder::onOBSInitialized);
                
                // 连接录制开始/停止信号到RTCRecorder的音频处理
                connect(recorderClient, &RecorderClient::OBSStartRecording, 
                        m_rtcRecorder, &RTCRecorder::startAudioProcessing);
                connect(recorderClient, &RecorderClient::OBSStopRecording, 
                        m_rtcRecorder, &RTCRecorder::stopAudioProcessing);
                
                // 连接推流开始/停止信号到RTCRecorder的音频处理（确保推流录制时也能订阅RTC音频）
                connect(recorderClient, &RecorderClient::OBSStartStreaming, 
                        m_rtcRecorder, &RTCRecorder::startAudioProcessing);
                connect(recorderClient, &RecorderClient::OBSStopStreaming, 
                        m_rtcRecorder, &RTCRecorder::stopAudioProcessing);
                
                qDebug() << "[RECORDER] RTCRecorder signals connected: OBS init, recording start/stop, streaming start/stop";
                qDebug() << "[RECORDER] RTC mode initialization order now identical to device mode";
            } else {
                qWarning() << "[RECORDER] Failed to get RecorderClient instance for signal connection";
            }
            
        } else {
            qDebug() << "[RECORDER] Entering device recording mode branch";
            // 设备录制模式 - 创建原始录制应用
            qDebug() << "[RECORDER] Creating device recorder for device recording mode";
            qDebug() << "[RECORDER] About to create ZDTalkRecorder instance...";
            m_recorderApp = new ZDTalkRecorder(this);
            if (!m_recorderApp) {
                qDebug() << "[RECORDER] FAILED to create recorder app";
                emit error("Failed to create recorder app");
                return false;
            }
            qDebug() << "[RECORDER] Device recorder created successfully";
            
            // 在初始化之前应用配置
            qDebug() << "[RECORDER] Applying recording configuration...";
            applyRecordingConfig(config);
            qDebug() << "[RECORDER] Recording configuration applied";
            
            // 初始化录制应用，使用配置中的服务器名称
            QString targetServerName = config.serverName.isEmpty() ? "ZDTalkRecorder" : config.serverName;
            qDebug() << "[RECORDER] Initializing device recorder with server name:" << targetServerName;
            
            qDebug() << "[RECORDER] About to call m_recorderApp->Init()...";
            if (m_recorderApp->Init(targetServerName, "") != 0) {
                qDebug() << "[RECORDER] FAILED to initialize recorder app";
                emit error("Failed to initialize recorder app");
                return false;
            }
            
            qDebug() << "[RECORDER] Device recorder initialized successfully";
        }
    } else {
        qDebug() << "[MMSERVICE] Student mode - no recording functionality needed";
    }
    
    qDebug() << "[MMSERVICE] RTCClient created for type:" << serviceType;
    
    m_initialized = true;
    qDebug() << "[MMSERVICE] MMService initialized successfully";
    
    return true;
}

void MMService::applyRecordingConfig(const RecordingConfig &config)
{
    if (!m_recorderApp) {
        qWarning() << "[RECORDER] Recorder app not available for config application";
        return;
    }
    
    qDebug() << "[RECORDER] Applying recording configuration to RecorderService...";
    
    // 将MMService的配置转换为RecorderService的配置
    ::RecorderConfig recorderConfig;
    recorderConfig.logPath = config.logPath;
    recorderConfig.crashPath = config.crashPath;
    recorderConfig.userName = config.userName;
    recorderConfig.userId = config.userId;
    recorderConfig.serverName = config.serverName;
    
    // 设置配置到录制应用
    m_recorderApp->SetConfig(recorderConfig);
    
    qDebug() << "[RECORDER] Recording configuration applied - Mode:" << config.recordingMode
             << "User:" << config.userName << "ID:" << config.userId;
    
    // 如果是RTC麦克风模式，输出音频参数信息
    if (config.recordingMode == "rtc-mic") {
        qDebug() << "[RECORDER] RTC Audio Config - Rate:" << config.rtcAudioSampleRate << "Hz"
                 << "Channels:" << config.rtcAudioChannels 
                 << "Format:" << config.rtcAudioFormat << "bit";
    }
}

// RTC Client 连接相关的处理已经在 initialize 中添加

void MMService::start()
{
    if (!m_initialized) {
        emit error("MMService not initialized");
        return;
    }
    
    qDebug() << "[MMSERVICE] Starting MMService...";
    
    // 只有教师端才启动录制服务
    if (m_serviceType == "teacher") {
        if (m_recorderApp) {
            qDebug() << "[MMSERVICE] Starting device recorder service for teacher mode";
            // 录制应用已经在初始化时启动，这里不需要额外操作
        }
        
        if (m_rtcRecorder) {
            qDebug() << "[MMSERVICE] Starting RTC recorder service for teacher mode";
            // RTC录制器已经在初始化时启动，这里不需要额外操作
        }
    }
    
    emit serviceStarted();
    qDebug() << "[MMSERVICE] MMService started successfully with type:" << m_serviceType;
}

// 添加一个公共槽函数，用于处理RTC客户端断开连接
void MMService::onRTCClientDisconnected()
{
    qDebug() << "[MMSERVICE] RTC Client disconnected, stopping recording and triggering service stop";
    
    // 如果是教师端且有录制应用，主动停止录制
    if (m_serviceType == "teacher") {
        if (m_recorderApp) {
            qDebug() << "[MMSERVICE] Device recording will be stopped by recorder service internal logic";
        }
        
        if (m_rtcRecorder) {
            qDebug() << "[MMSERVICE] RTC recording will be stopped by recorder service internal logic";
        }
    }
    
    emit serviceStopped();
}

void MMService::stop()
{
    if (!m_initialized) {
        return;
    }
    
    qDebug() << "[MMSERVICE] Stopping MMService...";
    
    // 优先停止录制服务
    if (m_serviceType == "teacher") {
        if (m_recorderApp) {
            qDebug() << "[MMSERVICE] Stopping device recorder service for teacher mode";
            // 通过录制服务内部的Socket通信停止录制
            // 录制服务会自动处理停止录制
        }
        
        if (m_rtcRecorder) {
            qDebug() << "[MMSERVICE] Stopping RTC recorder service for teacher mode";
            // RTC录制器会自动清理资源
        }
    }
    
    // 停止 RTC 客户端
    if (m_rtcClient) {
        qDebug() << "[MMSERVICE] Stopping RTC client...";
        // RTCClient 会在析构时自动断开连接
    }
    
    emit serviceStopped();
    qDebug() << "[MMSERVICE] MMService stopped successfully";
}



void MMService::onAudioFrameReceived(const QString &source, const ding::rtc::RtcEngineAudioFrame &frame)
{
    static int totalFrameCount = 0;
    static bool firstFrameLogged = false;
    totalFrameCount++;
    
    // 只在第一次接收到音频帧时输出日志
    if (!firstFrameLogged) {
        qDebug() << "[MMSERVICE] First audio frame received - source:" << source
                 << "initialized:" << m_initialized
                 << "serviceType:" << m_serviceType
                 << "recordingMode:" << m_recordingConfig.recordingMode
                 << "samples:" << frame.samples
                 << "channels:" << frame.channels
                 << "sampleRate:" << frame.samplesPerSec;
        firstFrameLogged = true;
    }
    
    if (!m_initialized || m_serviceType != "teacher") {
        return;
    }
    
    // 只在RTC麦克风模式下处理音频帧
    if (m_recordingConfig.recordingMode != "rtc-mic") {
        return;
    }
    
    // 只处理3A处理后的音频帧（processed）- 这样可以获取经过3A处理且受静音影响的音频
    if (source == "processed") {
        // 检查音频帧是否为有效数据（避免静音时的无效数据）
        if (!frame.buffer || frame.samples <= 0) {
            static int emptyFrameCount = 0;
            emptyFrameCount++;
            // 只在第一次和每1000次空帧时输出日志
            if (emptyFrameCount == 1 || emptyFrameCount % 1000 == 0) {
                qDebug() << "[MMSERVICE] Empty audio frame detected (count:" << emptyFrameCount << ") - likely muted";
            }
            return;
        }
        
        // 直接转发音频帧到RTC录制器
        if (m_rtcRecorder) {
            m_rtcRecorder->processAudioFrame(frame);
            
            // 记录处理统计 - 大幅降低频率
            static int processedFrameCount = 0;
            processedFrameCount++;
            if (processedFrameCount % 5000 == 0) {  // 每5000帧记录一次
                qDebug() << "[MMSERVICE] Processed" << processedFrameCount << "audio frames";
            }
        } else {
            qWarning() << "[MMSERVICE] RTC recorder not available";
        }
    }
}

void MMService::enableAudioFrameObserver()
{
    if (!m_initialized || m_serviceType != "teacher") {
        qWarning() << "[MMSERVICE] Cannot enable audio frame observer - service not initialized or not teacher mode";
        return;
    }
    
    if (m_recordingConfig.recordingMode != "rtc-mic") {
        qWarning() << "[MMSERVICE] Cannot enable audio frame observer - not in RTC microphone mode";
        return;
    }
    
    if (m_rtcClient) {
        qDebug() << "[MMSERVICE] Registering and enabling audio frame observer for RTC recording";
        
        // 先注册音频帧观察者（如果还没有注册的话）
        m_rtcClient->registerAudioFrameObserver();
        
        // 然后启用音频帧观察者
        m_rtcClient->enableAudioFrameObserver(true);
        
        qDebug() << "[MMSERVICE] Audio frame observer registered and enabled successfully";
    } else {
        qWarning() << "[MMSERVICE] RTC client not available for audio frame observer";
    }
}

void MMService::disableAudioFrameObserver()
{
    if (m_rtcClient) {
        qDebug() << "[MMSERVICE] Disabling audio frame observer";
        m_rtcClient->enableAudioFrameObserver(false);
    }
} 